var itemClass;
var ctx = ctx;
var applyId;
var rowNum = 0;
var patientId = "";
var clinicId = "";
var visitId = "";
var inoroutFlag = "";
$(function () {
    patientId = $("#patientIdVal").val();
    inoroutFlag = $("#inoroutFlag").val();
    if (inoroutFlag == '0') {
        visitId = "";
        clinicId = $("#clinicId").val();
    }
    if (inoroutFlag == '1') {
        visitId = $("#visitId").val();
        clinicId = "";
    }
    //$("#clinicIds").val(clinicId);
    $("#patientId").val(patientId);
    loadDiv('applyDiv', ctx + '/doctor/prescriptionApply/applyIndex?clinicId=' + clinicId + '&patientId=' + patientId + '&visitId=' + visitId);
    //loadDiv('prescWesternItemDiv', ctx + '/doctor/prescriptionItem/index?applyId='+applyId+'&inoroutFlag='+inoroutFlag);
});
/*保存处方至医嘱及医嘱明细表*/
function savePresc() {
    var charge = "";
    var status = "";
    if($("#applyTableId .table-selected").length>0){
        if(inoroutFlag == '0'){
            //1.获取选中行，判断其收费状态和是否已生成医嘱信息，如果已收费或者已保存到医嘱，则不允许添加药品
            charge = $("#applyTableId .table-selected").find("td").eq(5).find("input").val();
            status = $("#applyTableId .table-selected").find("td").eq(7).find("input").val();
        }else{
            //1.获取选中行，判断其收费状态和是否已生成医嘱信息，如果已收费或者已保存到医嘱，则不允许添加药品
            charge = $("#applyTableId .table-selected").find("td").eq(4).find("input").val();
            status = $("#applyTableId .table-selected").find("td").eq(5).find("input").val();
        }
        if((charge == 0 || charge == '0') && (status == 0 || status == '0')){
            /*判断有没有药品，如果有药品，再让进行保存操作*/
            //var clinicId=$("#clinicIdVal").val();
            //if(!clinicId){
            //    clinicId = '';
            //}
            if( $("#itemListTable tr").length>1 ||$(".drugCenterUl").find('li').length>0) {
                if (itemClass == 'B') {

                    var isDecoction = $("input[name='isDecoction']:checked").val();
                    if ($('#prescChineseItemForm').parsley().validate()) {
                        $.ajax({
                            type: "POST",
                            data: $("#prescChineseItemForm").serialize(),
                            url: ctx + "/doctor/prescriptionItem/saveChina?clinicId=" + clinicId + "&patientId=" + patientId + "&visitId=" + visitId,
                            dataType: "json",
                            success: function (data) {
                                if (data.code == "success") {
                                    toastr.success("保存成功");
                                    loadDiv('applyDiv', ctx + '/doctor/prescriptionApply/applyIndex?clinicId=' + clinicId + '&patientId=' + patientId + '&visitId=' + visitId);
                                    loadDiv('prescChineseItemDiv', ctx + '/doctor/prescriptionItem/chineseIndex?applyId=' + applyId);
                                } else {
                                    toastr.error(data.data);
                                }
                            },
                            error: function (data) {
                                toastr.error('网络连接错误,请检查网络');
                            }
                        });
                    }
                } else {
                    //var value =$("input[name='isTempla']");
                    //var isTempla = "";
                    //for(var i=0;i<value.length;i++){
                    //    if(value[i].checked){
                    //        isTempla = value[i].value;
                    //    }
                    //}
                    $.ajax({
                        type: "POST",
                        url: ctx + "/doctor/prescriptionItem/savePrescription?itemClass=A&applyId=" + applyId+"&inoroutFlag="+inoroutFlag+"&ordersFlag="+$("#ordersFlag").val()+"&clinicId="+clinicId,
                        success: function (data) {
                            if (data.code == "success") {
                                toastr.success(data.data);
                                loadDiv('applyDiv', ctx + '/doctor/prescriptionApply/applyIndex?clinicId=' + clinicId + '&patientId=' + patientId + '&visitId=' + visitId);
                            } else {
                                toastr.error(data.data);
                            }
                        },
                        error: function (data) {
                            toastr.error('网络连接错误,请检查网络');
                        }
                    });
                }
            }else{
                toastr.info("请添加药品后，再进行保存操作！");
                return false;
            }
        } else {
            toastr.info("此处方已保存，请勿重复提交!");
            return false;
        }}



}
//点击新方
//function newPresc(divId, formId, url, hrefUrl) {
//    if($("#applyTableId .table-selected").length>0){
//        var status = $("#applyTableId .table-selected").find("td").eq(6).find("input").val();
//        if(status==0||status=='0'){
//            toastr.info("请对新方进行保存后，再进行添加新方操作！");
//            return false;
//        }else{
//
//        }
//    }else{
//        var id = $("#applyTableId tbody .table-selected td:first").text();
//        url = url + "?id=" + id;
//        return formSaveLoad(divId, formId, url, hrefUrl);
//    }
//
//}
function newPresc(divId, formId, url, hrefUrl) {
    var id = $("#applyTableId tbody .table-selected td:first").text();
    url = url + "?id=" + id;
    return formSaveLoad(divId, formId, url, hrefUrl);
}


/*选中行*/
function applyClick(obj, tb,inoroutFlag) {
    applyId = obj;
    $("#applyId").val(applyId);
    var item = $(tb).find("td").eq(3).text();
    if (item == '草药') {
        itemClass = 'B';
        funItem(itemClass,inoroutFlag);
    } else {
        itemClass = 'A';
        funItem(itemClass,inoroutFlag);
    }
}
//西药/草药单选按钮事件
function funItem(obj,inoroutFlag) {
    itemClass = obj;
    if (itemClass == 'B') {
        $("#centrePerscription").show();
        $("#westPerscription").hide();
        loadDiv('prescChineseItemDiv', ctx + '/doctor/prescriptionItem/chineseIndex?applyId=' + applyId+'&inoroutFlag='+inoroutFlag);
    } else {
        $("#centrePerscription").hide();
        $("#westPerscription").show();
        loadDiv('prescWesternItemDiv', ctx + '/doctor/prescriptionItem/index?applyId=' + applyId+'&inoroutFlag='+inoroutFlag);
    }

    $("#itemClass").val(itemClass);

}
/*中西药局切换*/
function deptChange(inputId) {
    var value = $.trim($("#" + inputId).val());
    var text = $("#" + inputId + " option[value=" + value + "]").text();
    if (text == '西药局' || text == '西药房') {
        $("input:radio[value='A']").prop("checked", true);
    } else if (text == '中药局' || text == '中药房') {
        $("input:radio[value='B']").prop("checked", true);
    }
}
//选中处方行，更改radio选中值
function changeRadio(obj) {
    $("#itemClass").val(obj);
    itemClass = obj;
    $('input:radio[value=' + itemClass + ']').prop("checked", true);

}

/*添加药品*/
function addPrescItem(inoroutFlag) {
    var charge = "";
    var status = "";
     if($("#applyTableId .table-selected").length>0){
         if(inoroutFlag == '0'){
            //1.获取选中行，判断其收费状态和是否已生成医嘱信息，如果已收费或者已保存到医嘱，则不允许添加药品
             charge = $("#applyTableId .table-selected").find("td").eq(5).find("input").val();
             status = $("#applyTableId .table-selected").find("td").eq(7).find("input").val();
         }else{
             //1.获取选中行，判断其收费状态和是否已生成医嘱信息，如果已收费或者已保存到医嘱，则不允许添加药品
             charge = $("#applyTableId .table-selected").find("td").eq(4).find("input").val();
             status = $("#applyTableId .table-selected").find("td").eq(5).find("input").val();
         }
         if ((charge == 0 || charge == '0') && (status == 0 || status == '0')) {
             $("#prescWesternItemDiv").attr("class", " panel col-lg-6");
             hideShowTableTd("itemListTable", '3,4,6,7,8,11', '2');
             $("#prescWesternItemFormDiv").show('normal');
             loadDiv('prescWesternItemFormDiv', ctx + '/doctor/prescriptionItem/form?applyId=' + applyId+'&inoroutFlag='+inoroutFlag);
         } else {
             toastr.info("药品已保存或已生成药品费用，不能进行药品添加！");
             return false;
         }
     }else{
         toastr.info("未开新方不能进行药品添加操作！");
         return false;
     }


}
/*添加子处方*/
function subPresc(inoroutFlag) {
    var charge = "";
    var status = "";
    if(inoroutFlag == '0'){
        //1.获取选中行，判断其收费状态和是否已生成医嘱信息，如果已收费或者已保存到医嘱，则不允许添加药品
        charge = $("#applyTableId .table-selected").find("td").eq(5).find("input").val();
        status = $("#applyTableId .table-selected").find("td").eq(7).find("input").val();
    }else{
        //1.获取选中行，判断其收费状态和是否已生成医嘱信息，如果已收费或者已保存到医嘱，则不允许添加药品
        charge = $("#applyTableId .table-selected").find("td").eq(4).find("input").val();
        status = $("#applyTableId .table-selected").find("td").eq(5).find("input").val();
    }
    if ((charge == 0 || charge == '0') && (status == 0 || status == '0')) {
        var val = $("#itemListTable .table-selected").attr("id");
        var parentId = $("#itemListTable .table-selected").attr("pId");
        if (parentId==undefined || parentId==''){
            if (val != null) {
                /*添加药品表单显示，药品明细列表缩进并隐藏相应的列*/
                $("#prescWesternItemDiv").attr("class", " panel col-lg-6");
                hideShowTableTd("itemListTable", '3,4,6,7,8,11', '2');
                $("#prescWesternItemFormDiv").show('normal');
                var url = ctx + '/doctor/prescriptionItem/form?applyId=' + applyId + "&parent.id=" + val+"&inoroutFlag="+inoroutFlag;
                $("#prescWesternItemFormDiv").load(url,'',function(response,status,xhr){
                    $("select").select2({matcher: function (term, text) {
                        term = term.toUpperCase();
                        if (makePy(text)[0].indexOf(term) != -1 || text.indexOf(term) != -1) {
                            return text;
                        }
                        return "";
                    }
                    });
                    var chanel = $("#itemListTable .table-selected").find("td").eq(6).find("input").val();
                    var freq = $("#itemListTable .table-selected").find("td").eq(7).find("input").val();
                    /*回填父处方途径和频次*/
                    $("#channel option[value='"+chanel+"']").attr("selected","selected");
                    $("#channel").change();
                    $("#frequency option[value='"+freq+"']").attr("selected","selected");
                    $("#frequency").change();

                });
            } else {
                toastr.error("请先选择父处方");
            }
        }else{
            toastr.info("不能为子处方添加子处方，请选择父处方");
        }

    } else {
        toastr.info("药品已保存或已生成药品费用，不能进行药品添加！");
    }

}
//根据用药数量计算费用
function changeSumPrice(numId, priceId, sumPriceId) {

    var num = $.trim($("#" + numId).val());
    var price = $.trim($("#" + priceId).val());
    var sum = Number(num) * Number(price);
    $("#" + sumPriceId).val(sum.toFixed(4));
}
//用药途径更改为皮试途径时，是否皮试为是
function adminDictFun(obj, isInputId,inoroutFlag) {
    var parentId = $("#itemListTable .table-selected").attr("pId");
    var dict = $("#channel option[value=" + obj.value + "]").text();
    if (dict == '皮试' || dict == '皮试用') {
        $("#" + isInputId + " option[value=1]").attr("selected", true);
    } else {
        $("#" + isInputId + " option[value=1]").removeAttr("selected", true);
    }
    if( parentId != null){
        subPresc(inoroutFlag);
    }

}

/*删除西药明细*/
function deleteLoad(applyDiv,itemDiv,url,applyUrl,itemUrl){
    url=timestamp(url);
    applyUrl=timestamp(applyUrl);
    itemUrl=timestamp(itemUrl);
    $.ajax({
        type: "POST",
        url: url,
        dataType: "json",
        success: function (data) {
            if (data.code == "success") {
                toastr.success(data.data);
                loadDiv(applyDiv, applyUrl);
                loadDiv(itemDiv, itemUrl);
            } else if (data.code == "info") {
                toastr.info(data.data);
            } else {
                toastr.error(data.data);
            }
        },
        error: function (data) {
            toastr.error('网络连接错误,请检查网络');
        }
    });
}

function addPrescItemTemplate(projectType,creator,deptCode,clinicId,patientId,visitId,inoroutFlag) {
    var charge = "";
    var status = "";
    var itemClass = "";
    if ($("#applyTableId .table-selected").length > 0) {
        if (inoroutFlag == '0') {
            //1.获取选中行，判断其收费状态和是否已生成医嘱信息，如果已收费或者已保存到医嘱，则不允许添加药品
            charge = $("#applyTableId .table-selected").find("td").eq(5).find("input").val();
            status = $("#applyTableId .table-selected").find("td").eq(7).find("input").val();
            itemClass = $("#applyTableId .table-selected").find("td").eq(3).find("input").val();
        } else {
            //1.获取选中行，判断其收费状态和是否已生成医嘱信息，如果已收费或者已保存到医嘱，则不允许添加药品
            charge = $("#applyTableId .table-selected").find("td").eq(4).find("input").val();
            status = $("#applyTableId .table-selected").find("td").eq(5).find("input").val();
        }
        if ((charge == 0 || charge == '0') && (status == 0 || status == '0')) {
            var itemClass =  $("#applyTableId .table-selected").find("td").eq(3).find("input").val();
            var applyId =  $("#applyTableId .table-selected").find("td").eq(0).text();
            //if(itemClass == "A"){
                layer.open({
                    type: 2,
                    title:'处方模板',
                    area: ['60%', '85%'],
                    fixed: false, //不固定
                    maxmin: true,
                    content: ctx+'/doctor/outpTreatRec/indexTreat?type='+projectType+'&creator='+creator+'&deptCode='+deptCode+'&clinicId='+clinicId+'&visitId='+visitId+'&patientId='+patientId+'&prescApplyId='+applyId+'&inoroutFlag='+inoroutFlag+'&itemClass='+itemClass
                });
            //} else {
            //    toastr.info("请选择西药处方，添加药品！");
            //    return false;
            //}

        } else {
            toastr.info("药品已保存或已生成药品费用，不能进行模板添加！");
            return false;
        }
    } else {
        toastr.info("未开新方不能进行药品添加操作！");
        return false;
    }
}
